package com.technology.education.ext

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.*
import android.view.View
import androidx.annotation.NonNull
import com.technology.education.widget.NolineClickableSpan
import com.technology.education.MyApplication
import com.technology.education.R
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.text.DecimalFormat
import java.util.*
import kotlin.math.abs

/**
 *@author:create by BZY
 *Date: 2020/6/16 16
 */

fun getSpan(context: Context): CharSequence {
    val convertString =
        "我已阅读并同意《服务协议》和《隐私政策》"
    val spannableString = SpannableString(convertString)
    spannableString.setSpan(
        ForegroundColorSpan(
            getColor(
                R.color.text_h
            )
        ),
        7,
        14,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    spannableString.setSpan(
        ForegroundColorSpan(
            getColor(
                R.color.text_h
            )
        ),
        14,
        15,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    spannableString.setSpan(
        object : NolineClickableSpan() {
            override fun onClick(@NonNull widget: View) {

            }
        },
        7,
        13,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    spannableString.setSpan(
        object : NolineClickableSpan() {
            override fun onClick(@NonNull widget: View) {

            }
        },
        14,
        convertString.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    return spannableString
}

/**
 * 校验身份号
 */
fun checkIdCard(idCard: String?): Boolean {
    if (idCard?.length != 18) {
        return false
    }
    val lastDigit: String = idCard.substring(17)
    val x = intArrayOf(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)

    val y = charArrayOf('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')

    var sum = 0

    for (i in 0..16) {
        val n: Int = idCard[i].toInt() - 48
        sum += n * x[i]
    }
    sum %= 11

    val a = y[sum]

    return lastDigit.toUpperCase() == y[sum].toString()
}

/**
 * 使用deeplink 传参时，参数为null时，接收到的参数为"null" ,所以这里扩展函数，增加null值的判断条件
 * */
fun String.isNotEmpty(): Boolean {
    return !isNullOrEmpty() && this != "null"
}

/**
 * 将list 转化为逗号分隔的string
 */
fun List<String>.toSplitString(): String {
    var result = ""
    this?.forEach {
        result += ",$it"
    }
    if (result.isNotEmpty()) {
        result = result.substring(1)
    }
    return result
}

fun String?.isNull(): Boolean {
    return isNullOrEmpty() || this == "null"
}

fun String.copyToClip(context: Context?) {
    context?.apply {
        var clm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        clm.setPrimaryClip(ClipData.newPlainText("keyi", this@copyToClip))
    }

}

fun getDistance(distance: Int): String? {
    return if (distance < 1000) {
        distance.toString() + "m"
    } else {
        (distance / 1000).toString() + "km"
    }
}

fun getFomatDouble(value: Double): String {
    val df = DecimalFormat("#0.00")
    return df.format(value)
}

fun getFomatDouble(value: String?): String {
    if (value.isNull()) {
        return ""
    }
    val df = DecimalFormat("#0.00")
    value?.let {
        return "¥${df.format(value.toDouble())}"
    } ?: return ""
}

/**
 * String 转换为 map
 */
fun transStringToMap(
    mapString: String,
    separator: String?,
    pairSeparator: String?
): Map<String, Any>? {
    val map: MutableMap<String, Any> =
        HashMap()
    val fSplit: Array<String?> = mapString.split(separator!!).toTypedArray()
    for (i in fSplit.indices) {
        if (fSplit[i] == null || fSplit[i]!!.length == 0) {
            continue
        }
        val sSplit = fSplit[i]!!.split(pairSeparator!!).toTypedArray()
        val value = fSplit[i]!!.substring(fSplit[i]!!.indexOf('=') + 1)
        map[sSplit[0]] = value
    }
    return map
}

fun getMiddleColor(start: String, middle: String, end: String, middleColor: Int): SpannableString {
    val convertString = start + middle + end
    val spannableString = SpannableString(convertString)
    if (abs(middleColor) > 0) {
        spannableString.setSpan(
            ForegroundColorSpan(middleColor),
            start.length,
            convertString.length - end.length,
            33
        )
    }

    return spannableString
}

fun getMiddleSize(start: String, middle: String, end: String): SpannableString {
    val convertString = start + middle + end
    val spannableString = SpannableString(convertString)
    spannableString.setSpan(
        RelativeSizeSpan(0.6f),
        start.length,
        convertString.length - end.length,
        33
    )

    return spannableString
}

fun getMiddleBorderColor(
    start: String,
    middle: String,
    end: String,
    middleColor: Int
): SpannableString {
    val convertString = start + middle + end
    val spannableString = SpannableString(convertString)
    if (abs(middleColor) > 0) {
        spannableString.setSpan(
            ForegroundColorSpan(getColor(middleColor)),
            start.length,
            convertString.length - end.length,
            33
        )
        spannableString.setSpan(
            StyleSpan(Typeface.BOLD),
            start.length,
            convertString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
    }

    return spannableString
}

fun getEndBorderColor(start: String, end: String, middleColor: Int): SpannableString {
    val convertString = start + end
    val spannableString = SpannableString(convertString)

    if (abs(middleColor) > 0) {
        spannableString.setSpan(
            ForegroundColorSpan(getColor(middleColor)),
            start.length,
            convertString.length,
            33
        )
        spannableString.setSpan(
            StyleSpan(Typeface.BOLD),
            start.length,
            convertString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
    }

    return spannableString
}

/**
 * text 中间删除线
 */
fun getDeleteString(origin: String): SpannableString {
    var origin = origin
    if (TextUtils.isEmpty(origin)) {
        origin = ""
    }
    val spanStrikethrough = SpannableString(origin)
    spanStrikethrough.setSpan(
        StrikethroughSpan(),
        0,
        origin.length,
        Spannable.SPAN_INCLUSIVE_EXCLUSIVE
    )
    return spanStrikethrough
}
/**
 * 三峡评价页面满意度调查
 */
fun getSxyyNotifyString(origin: String,clickableSpan: ClickableSpan?): SpannableString {
    var origin = origin
    if (TextUtils.isEmpty(origin)) {
        origin = ""
    }
    val spanStrikethrough = SpannableString(origin)
//    spanStrikethrough.setSpan(
//        UnderlineSpan(),
//        0,
//        origin.length,
//        Spannable.SPAN_INCLUSIVE_EXCLUSIVE
//    )

    spanStrikethrough.setSpan(
        clickableSpan,
        origin.length-6,
        origin.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    return spanStrikethrough
}

/**
 * 读取本地json数据
 */
fun getJson(fileName: String): String{
    val stringBuilder = StringBuilder()
    try {
        val assetManager = MyApplication.context.assets
        val bf = BufferedReader(
            InputStreamReader(
                assetManager.open(fileName)
            )
        )
        var line: String?
        while (bf.readLine().also { line = it } != null) {
            stringBuilder.append(line)
        }
        bf.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return stringBuilder.toString()
}

/**
 * 为中间字符串添加点击事件同时修改字体颜色
 *
 * @param start
 * @param middle
 * @param end
 * @param colorRes
 * @param clickableSpan 点击回调
 * @return
 */
fun getClickString(
    start: String,
    middle: String,
    end: String,
    colorRes: Int,
    clickableSpan: ClickableSpan?
): SpannableString? {
    val convertString = start + middle + end
    val spannableString = SpannableString(convertString)
    spannableString.setSpan(
        ForegroundColorSpan(
            getColor(
                colorRes
            )
        ),
        start.length,
        convertString.length - end.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    spannableString.setSpan(
        clickableSpan,
        start.length,
        convertString.length - end.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    return spannableString
}
